<template>
  <div v-loading="loading">
    <el-form ref="form" :model="form" :rules="rules" label-width="120px" class="dataForm">
      <el-row>
        <el-col v-if="this.$route.query.id != null" :span="12">
          <el-form-item :label="$t('基金名称')" prop="fundName">
            <el-input v-model="form.fundName" disabled :placeholder="$t('基金名称')" show-word-limit maxlength="32" />
          </el-form-item>
        </el-col>
        <el-col v-if="this.$route.query.id == null" :span="12">
          <el-form-item :label="$t('基金名称')" prop="fundId">
            <MainBodySelect
              v-model="form.fundId"
              parameters="fund"
              :disabled="true"
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item :label="$t('项目名称')" prop="associatedId">
            <!--            <deal-select v-model="form.associatedId" :investment-id="form.fundId" @change="formatCurrencyByDealId($event)" />-->
            <el-select v-model="form.associatedId" filterable clearable>
              <el-option
                v-for="item in dealList"
                :key="item.id"
                :label="item.name"
                :value="item.id"
              />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item :label="$t('现金流类型')" prop="type">
            <el-select v-model="form.type" :placeholder="$t('现金流类型')">
              <el-option
                v-for="dict in typeOptions"
                :key="dict.dictValue"
                :label="$t(dict.dictLabel)"
                :value="dict.dictValue"
              />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item :label="$t('业务类型')" prop="operateType">
            <el-select v-model="form.operateType" :placeholder="$t('业务类型')">
              <el-option
                v-for="dict in operateTypeOptions"
                :key="dict.dictValue"
                :label="$t(dict.dictLabel)"
                :value="dict.dictValue"
              />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item :label="$t('方向')" prop="direction">
            <el-radio-group v-model="form.direction">
              <el-radio
                v-for="dict in directionOptions"
                :key="dict.dictValue"
                :label="dict.dictValue"
              >{{ $t(dict.dictLabel) }}
              </el-radio>
            </el-radio-group>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item :label="$t('权益变更时间')" prop="equityChangeTime">
            <DatePicker
              v-model="form.equityChangeTime"
              :placeholder="$t('权益变更时间')"
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item :label="$t('发生时间')" prop="operateDate">
            <DatePicker
              v-model="form.operateDate"
              :placeholder="$t('发生时间')"
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item :label="$t('发生金额') + $t('(元)')" prop="operateAmount">
            <Money v-model="form.operateAmount" :placeholder="$t('发生金额')" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item :label="$t('币种')" prop="currency">
            <dictSelect
              v-model="form.currency"
              :clearable="true"
              dictionary="currency"
              @change="changeCurr"
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item v-show="isRate || (form.exchangeRate && form.operateRmb)" :label="$t('汇率') " prop="exchangeRate">
            <el-input-number v-model="form.exchangeRate" controls-position="right" :min="0" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item v-show="isRate || (form.exchangeRate && form.operateRmb)" :label="$t('发生金额') + formatCurrencyByDealIdName + $t('(元)')" prop="operateRmb">
            <money v-model="form.operateRmb" />
          </el-form-item>
        </el-col>
        <!--        <el-col :span="12">-->
        <!--          <el-form-item :label="$t('是否参与IRR计算')" prop="whetherIrr">-->
        <!--            <el-radio-group v-model="form.whetherIrr">-->
        <!--              <el-radio-->
        <!--                v-for="dict in whetherIrrOptions"-->
        <!--                :key="dict.dictValue"-->
        <!--                :label="dict.dictValue"-->
        <!--              >{{ $t(dict.dictLabel) }}-->
        <!--              </el-radio>-->
        <!--            </el-radio-group>-->
        <!--          </el-form-item>-->
        <!--        </el-col>-->
        <el-col v-if="form.direction === 'LR'" :span="12">
          <el-form-item :label="$t('流入类型')" prop="incomeType">
            <el-radio-group v-model="form.incomeType">
              <el-radio
                v-for="dict in incomeTypeOptions"
                :key="dict.dictValue"
                :label="dict.dictValue"
              >{{ $t(dict.dictLabel) }}
              </el-radio>
            </el-radio-group>
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item :label="$t('备注')" prop="remark">
            <el-input v-model="form.remark" type="textarea" :placeholder="$t('备注')" show-word-limit maxlength="2000" />
          </el-form-item>
        </el-col>
      </el-row>
      <FileTable :list.sync="form.fileList" data-type="fund_cashflow" :business-id="autoBusinessId($route.query.id, form)" />
    </el-form>
    <div slot="footer" class="dialog-footer" style="text-align: right;">
      <!--保存，保存并启动流程，取消 三个按钮-->
      <SaveBtn has-permi="fund:cashflow" />
    </div>
  </div>
</template>

<script>
import { saveFundCashflow, getFundCashflow, findDealList } from '@/api/fund/cashflow/fundCashflow'
import { getFundBase } from '@/api/fund/fundBase'
import { getDealBase } from '@/api/base/deal/dealBase.js'
import MainBodySelect from '@/components/MainBodySelect'
import { getSystemCurrency } from '@/api/system/config'

export default {
  components: {
    MainBodySelect
  },
  data() {
    return {
      // 现金流类型  预计 实际字典
      typeOptions: [], // 方向：流入、流出字典
      directionOptions: [], // 类型：投资、回款、费用字典
      operateTypeOptions: [], // 是否参与IRR计算字典
      whetherIrrOptions: [], // 流入类型，收益，本金字典
      incomeTypeOptions: [], // 表单参数
      dealList: [], // 投资组合列表
      form: {
        fileList: []
      },
      // 遮罩层
      loading: false,
      isRate: false,
      curr: '',
      currencyOptions: [],
      formatCurrencyByDealIdName: '',
      // 表单校验
      rules: {
        type: [
          { required: true, message: this.$t('必填信息'), trigger: 'blur' }
        ], fundId: [
          { required: true, message: this.$t('必填信息'), trigger: 'blur' }
        ], operateDate: [
          { required: true, message: this.$t('必填信息'), trigger: 'blur' }
        ], operateAmount: [
          { required: true, message: this.$t('必填信息'), trigger: 'blur' }
        ], direction: [
          { required: true, message: this.$t('必填信息'), trigger: 'blur' }
        ], operateType: [
          { required: true, message: this.$t('必填信息'), trigger: 'blur' }
        ], whetherIrr: [
          { required: true, message: this.$t('必填信息'), trigger: 'blur' }
        ], incomeType: [
          { required: true, message: this.$t('必填信息'), trigger: 'blur' }
        ], currency: [
          { required: true, message: this.$t('必填信息'), trigger: 'blur' }
        ], exchangeRate: [
          { required: true, message: this.$t('必填信息'), trigger: 'blur' }
        ], operateRmb: [
          { required: true, message: this.$t('必填信息'), trigger: 'blur' }
        ], dpi: [
          { required: true, message: this.$t('必填信息'), trigger: 'blur' }
        ], equityChangeTime: [
          { required: true, message: this.$t('必填信息'), trigger: 'blur' }
        ]
      }
    }
  },
  created() {
    getSystemCurrency().then(res => {
      if (res.code === 200) {
        this.curr = res.data
      } else {
        this.msgError(res.msg)
      }
    })
    this.getDicts('cash_flow_type').then(response => {
      this.typeOptions = response.data
    })
    this.getDicts('cash_flow_direction').then(response => {
      this.directionOptions = response.data
    })
    this.getDicts('fund_cash_flow_type').then(response => {
      this.operateTypeOptions = response.data
    })
    this.getDicts('sys_yes_no').then(response => {
      this.whetherIrrOptions = response.data
    })
    this.getDicts('income_type').then(response => {
      this.incomeTypeOptions = response.data
    })
    this.getDicts('currency').then(response => {
      this.currencyOptions = response.data
    })
  },
  methods: {
    // 初始化数据
    init(data) {
      this.loading = true
      if (data != null && data.id !== undefined) {
        getFundCashflow(data.id).then(response => {
          this.form = response.data
          this.formatCurrencyByDealId(this.form.associatedId)
          this.findDealList(this.form.fundId)
          this.loading = false
          this.$forceUpdate()
        })
      } else {
        this.reset()
        if (this.$route.query.id != null) {
          getFundBase(this.$route.query.id).then(response => {
            this.form.fundName = response.data.fundName
            this.findDealList(this.form.fundId)
            this.loading = false
          })
        }
      }
    },
    // 表单重置
    reset() {
      this.form = {
        id: undefined,
        type: 'SJ',
        fundId: this.$route.query.id,
        fundName: undefined,
        dataId: undefined,
        component: undefined,
        operateDate: undefined,
        equityChangeTime: undefined,
        operateAmount: undefined,
        direction: undefined,
        operateType: undefined,
        whetherIrr: 'Y',
        incomeType: undefined,
        associatedId: undefined,
        remark: undefined,
        fileList: [],
        createBy: undefined,
        createTime: undefined,
        updateBy: undefined,
        updateTime: undefined,
        delFlag: undefined,
        currency: undefined,
        exchangeRate: undefined,
        operateRmb: undefined,
        dpi: undefined
      }
      this.resetForm('form')
    },
    // 取消按钮
    cancel() {
      this.$parent.$parent.formOpen = false
      this.$parent.$parent.reset()
    },
    // 关闭form页面
    closeForm() {
      // 关闭form页面遮罩层
      this.loading = false
      // 关闭form页面
      this.$parent.$parent.formOpen = false
      // 刷新list页面
      this.$parent.$parent.getList()
    },
    /** 提交按钮 */
    submitForm: function() {
      if (this.form.exchangeRate === undefined || this.form.exchangeRate === null || this.form.exchangeRate === '' || this.form.exchangeRate === 0) {
        this.form.exchangeRate = 1
      }
      if (this.form.operateRmb === undefined || this.form.operateRmb === null || this.form.operateRmb === '' || this.form.operateRmb === 0) {
        this.form.operateRmb = this.form.operateAmount
      }
      this.$refs['form'].validate(valid => {
        if (valid) {
          this.loading = true
          saveFundCashflow(this.form).then(response => {
            if (response.code === 200) {
              this.msgSuccess(this.$t('保存成功'))
              this.closeForm()
            } else {
              this.msgError(response.msg)
            }
            this.loading = false
          }).catch(() => {
            this.loading = false
          })
        } else {
          this.locationError(document)
        }
      })
    },
    // 改变币种触发事件
    changeCurr() {
      if (this.curr !== this.form.currency) {
        this.isRate = true
      } else {
        this.isRate = false
      }
      this.$nextTick(() => {
        this.$forceUpdate()
      })
      this.$forceUpdate()
    },
    /**
     * 获取当前主体币种名称
     * @param associatedId
     */
    formatCurrencyByDealId(associatedId) {
      if (associatedId) {
        getDealBase(associatedId).then(response => {
          if (response.data !== null) {
            this.formatCurrencyByDealIdName = '(' + this.$t(this.formatCurrency(response.data.currency)) + ') - '
          }
        })
      }
    },
    formatCurrency(val) {
      const currency = this.currencyOptions.find(obj => obj.dictValue === val)
      if (currency) {
        return currency.dictLabel
      }
      return ''
    },
    // 查询投资组合项目列表
    findDealList() {
      findDealList(this.form.fundId).then(response => {
        if (response.data !== null) {
          this.dealList = response.data
        }
      })
    }

  }

}
</script>
